package com.student.manage.service;

import com.student.manage.entity.LoginToken;
import com.student.manage.entity.User;
import com.student.manage.entity.model.LoginResult;
import com.student.manage.entity.model.RegisterResult;
import com.student.manage.entity.model.UpdateResult;
import com.student.manage.entity.model.UserTokenInfo;
import com.student.manage.entity.vo.UserLoginVo;
import com.student.manage.entity.vo.UserRegisterVo;
import com.student.manage.mapper.LoginTokenMapper;
import com.student.manage.mapper.UserMapper;
import com.student.manage.util.DigestUtils;
import com.student.manage.util.HttpServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Resource
    UserMapper userMapper;

    @Resource
    LoginTokenMapper loginTokenMapper;

    @Override
    public RegisterResult register(UserRegisterVo userRegisterVo) {

        Map<String, String> errorMsg = new HashMap<>();

        if (!StringUtils.hasText(userRegisterVo.getUsername())) {
            errorMsg.put("username", "用户名不能为空");
        }
        if (!StringUtils.hasText(userRegisterVo.getEmail())) {
            errorMsg.put("email", "邮箱不能为空");
        }
        if (!StringUtils.hasText(userRegisterVo.getPassword())) {
            errorMsg.put("password", "密码不能为空");
        }


        if (!StringUtils.hasText(userRegisterVo.getMobile())) {
            errorMsg.put("mobile", "手机号码不能为空");
        }


        User exist = userMapper.selectByUsername(userRegisterVo.getUsername());
        if (exist != null) {
            errorMsg.put("username", "用户名已存在");
        }
        if (errorMsg.size() > 0) {
            return RegisterResult.fail("注册失败", errorMsg);
        }

        User user = new User();
        user.setUsername(userRegisterVo.getUsername());
        user.setEmail(userRegisterVo.getEmail());
        user.setPassword(DigestUtils.sha256(userRegisterVo.getPassword()));
        user.setMobile(userRegisterVo.getMobile());
        user.setType(userRegisterVo.getType());

        userMapper.insert(user);

        return RegisterResult.success(user);
    }

    @Override
    public LoginResult login(UserLoginVo userLoginVo) {

        Map<String, String> errors = new HashMap<>();
        String username = userLoginVo.getUsername();

        if (!StringUtils.hasText(username)) {
            errors.put("username", "用户名不能为空");
        }

        String password = userLoginVo.getPassword();

        if (!StringUtils.hasText(password)) {
            errors.put("password", "密码不能为空");
        }

        String captchaCode = userLoginVo.getCaptchaCode();


        if (!StringUtils.hasText(captchaCode)) {
            errors.put("captchaCode", "验证码不能为空");
        }
        String code = HttpServletUtil.getSessionAttribute("captcha_code");
        log.info("session code: {}", code);
        if (!StringUtils.hasText(code)) {
            errors.put("captchaCode", "验证码已失效");
        } else if (!code.equalsIgnoreCase(captchaCode)) {
            errors.put("captchaCode", "验证码错误");
        }

        if (errors.size() > 0) {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            return LoginResult.fail(user, errors);
        }

        User dbUser = userMapper.selectByUsername(username);

        if (dbUser == null) {
            errors.put("username", "用户名不存在");
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            return LoginResult.fail(user, errors);
        }

        if (!DigestUtils.sha256(password).equals(dbUser.getPassword())) {
            errors.put("password", "密码错误");
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            return LoginResult.fail(user, errors);
        }

        HttpServletUtil.removeSessionAttribute("captcha_code");

        LoginToken loginToken = new LoginToken();
        loginToken.setUserId(dbUser.getId());
        loginToken.setCreateTime(LocalDateTime.now());

        //设置七天失效
        loginToken.setExpireTime(loginToken.getCreateTime().plusDays(LoginToken.DEFAULT_EXPIRE_TIME.toDays()));

        loginToken.setToken(DigestUtils.generateToken(username + password));

        loginToken.setStatus(LoginToken.Status.VALID.getCode());

        loginTokenMapper.insert(loginToken);
        return LoginResult.success(loginToken, dbUser);
    }

    @Override
    public List<User> list() {
        List<User> list = userMapper.selectList();
        return list;
    }

    @Override
    public UserTokenInfo getUserTokenInfo(String loginToken) {
        LoginToken token = loginTokenMapper.selectByToken(loginToken);

        if (token == null) {
            return null;
        }
        if (token.getStatus() != LoginToken.Status.VALID.getCode()) {
            return null;
        }

        User user = userMapper.selectByPrimaryKey(token.getUserId());

        if (user == null) {
            return null;
        }

        UserTokenInfo userTokenInfo = new UserTokenInfo(token, user);
        return userTokenInfo;
    }

    @Override
    public User getById(Integer id) {

        User user = userMapper.selectByPrimaryKey(id);

        return user;
    }

    @Override
    public UpdateResult updateByIdSelective(User user) {

        if (!StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(DigestUtils.sha256(user.getPassword()));
        }

        int count = userMapper.updateByPrimaryKeySelective(user);
        if (count > 0) {
            return UpdateResult.success(user);
        }
        return UpdateResult.error(user, null);
    }

    @Override
    public int deleteById(Integer id) {
        int count = userMapper.deleteByPrimaryKey(id);
        return count;
    }
}
